/*
 * @FilePath: \Src\BSP\src\drv_timer.c
 * @Description: 
 * 
 * Copyright (c) 2025 by ${w}, All Rights Reserved. 
 */

#include "main.h"

/**
 * @LastEditTime: 2025-06-10
 * @Description: 定时器硬件初始化
 *              基本定时器的时钟来自APB1,当PPRE1 ≥ 2分频的时候
 *              基本定时器的时钟为APB1时钟, 而APB1为72M
 *              定时器溢出时间计算方法: Tout = ((arr + 1) * (psc + 1)) / Ft us.
 *              Ft=定时器工作频率,单位:Mhz
 * @param {uint16_t} arr
 * @param {uint16_t} psc
 * @return {}
 */
void drv_timer16_init(uint16_t arr, uint16_t psc)
{
    timer_parameter_struct timer16_initpara;
    /* 使能TIMER6时钟 */
    rcu_periph_clock_enable(RCU_TIMER16);
    /* 复位TIMER6 */
    timer_deinit(TIMER16);
    /* 初始化为默认值 */
    timer_struct_para_init(&timer16_initpara);
    /* 配置TIMER6 */
    timer16_initpara.alignedmode         = TIMER_COUNTER_EDGE;
    timer16_initpara.prescaler           = psc - 1;          /* 分频值 */
    timer16_initpara.period              = arr - 1;          /* 装载值 */
    timer16_initpara.counterdirection    = TIMER_COUNTER_UP; /* 计数放式 */
    timer16_initpara.clockdivision       = TIMER_CKDIV_DIV1; /* 时钟分频 */
    timer16_initpara.repetitioncounter   = 0;
    timer_init(TIMER16, &timer16_initpara);
    /* 使能中断 */
    timer_interrupt_enable(TIMER16, TIMER_INT_UP);           /* 使能更新中断 */
    /* 配置优先级 */
    nvic_irq_enable(TIMER16_IRQn, 3);
    /* 使能定时器*/
    timer_enable(TIMER16);
}

/**
 * @LastEditTime: Do not edit
 * @Description: 
 * @return {}
 */
void TIMER16_IRQHandler(void)
{
    /* 更新中断是否发生 */
    if(timer_interrupt_flag_get(TIMER16, TIMER_INT_FLAG_UP) == SET)
    {
        /* 每隔1ms系统时间线++ */
        sys_timer.System_Ticks ++;

        /* 为io设备提供的系统时基 */
        io_tick_inc();

        /* 10ms任务标志 */
        if(sys_timer.System_Ticks % pdMS_TO_TICK(10) == 0)
        {
            sys_timer.System_10ms = 1;
        }

        /* 500ms任务标志 */
        if(sys_timer.System_Ticks % pdMS_TO_TICK(500) == 0)
        {
           sys_timer.System_500ms = 1;
        }

        /* 2s任务标志 */
        if(sys_timer.System_Ticks % pdMS_TO_TICK(2000) == 0)
        {
           sys_timer.System_2s = 1;
        }

        /* 3s任务标志 */
        if(sys_timer.System_Ticks % pdMS_TO_TICK(3000) == 0)
        {
           sys_timer.System_3s = 1;
        }

        /* 4s任务标志 */
        if(sys_timer.System_Ticks % pdMS_TO_TICK(4000) == 0)
        {
           sys_timer.System_4s = 1;
        }

        /* 清除更新中断*/
        timer_interrupt_flag_clear(TIMER16, TIMER_INT_FLAG_UP);
    }
}
